package com.ocean.web.controller.index;

import com.alibaba.fastjson.JSON;
import com.ocean.common.core.domain.AjaxResult;
import com.ocean.common.core.domain.entity.Config;
import com.ocean.common.core.domain.entity.SysDept;
import com.ocean.common.core.page.ForeResult;
import com.ocean.common.utils.EncodingUtil;
import com.ocean.common.utils.ShiroUtils;
import com.ocean.common.utils.StringUtils;
import com.ocean.common.utils.file.PoiExcelToHtmlUtils;
import com.ocean.common.utils.file.PptToHtmlUtils;
import com.ocean.common.utils.file.WordToHtmlUtils;
import com.ocean.common.utils.swf.ConStant;
import com.ocean.metadata.domain.OMetadataElement;
import com.ocean.metadata.service.IOMetadataElementService;
import com.ocean.nc.domain.ONcFile;
import com.ocean.nc.domain.ONcUnzip;
import com.ocean.nc.service.IONcFileService;
import com.ocean.nc.service.IONcUnzipService;
import com.ocean.previewElement.domain.PreviewData;
import com.ocean.previewElement.service.IOPreviewElementService;
import com.ocean.product.domain.OProduct;
import com.ocean.product.domain.OProductImage;
import com.ocean.product.domain.TSAttachment;
import com.ocean.product.service.IOProductImageService;
import com.ocean.product.service.IOProductService;
import com.ocean.product.service.ITSAttachmentService;
import com.ocean.productDict.domain.OForecastElement;
import com.ocean.productDict.domain.OMode;
import com.ocean.productDict.domain.ONCfileMenu;
import com.ocean.productDict.domain.OOceanArea;
import com.ocean.productDict.service.IOForecastElementService;
import com.ocean.productDict.service.IOModeService;
import com.ocean.productDict.service.IOOceanAreaService;
import com.ocean.productDict.service.ONCfilemeunService;
import com.ocean.system.domain.ODownOrder;
import com.ocean.system.service.IODownOrderService;
import com.ocean.system.service.ISysDeptService;
import com.ocean.workOrder.domain.OWorkOrder;
import com.ocean.workOrder.service.IOWorkOrderService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/home/productBrowsing")
public class ProductBrowsingController {
    private String prefix = "index/productbrowsing";

    @Autowired
    private IOProductService productService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IOForecastElementService forecastElementService;
    @Autowired
    private IOOceanAreaService oceanAreaService;
    @Autowired
    private IOModeService modeService;
    @Autowired
    private ITSAttachmentService attachmentService;
    @Autowired
    private IONcFileService ncFileService;
    @Autowired
    private IOMetadataElementService metadataElementService;
    @Autowired
    private IOWorkOrderService workOrderService;
    @Autowired
    private IOPreviewElementService previewElementService;
    @Autowired
    private IONcUnzipService ncUnzipService;
    @Autowired
    private IOProductImageService productImageService;
    @Autowired
    private IODownOrderService downOrderService;
    @Autowired
    private ONCfilemeunService onCfilemeunService;

    /**
     * 登录前菜单
     *
     * @return
     */
    @GetMapping("menu")
    @ResponseBody
    public AjaxResult index() {
        Map<String, List<String>> menu3 = productService.selectTypeAndDeptIsOpen();
        return AjaxResult.success(menu3);
    }

    /**
     * 登录后菜单
     *
     * @return
     */
    @GetMapping("menuLoggedIn")
    @ResponseBody
    public AjaxResult menuLoggedIn() {
        Map<String, Map<String, List<String>>> menu3 = productService.selectTypeAndDeptIsOpenLoggedIn();
        return AjaxResult.success(menu3);
    }

    /**
     * 是否登录状态
     *
     * @return
     */
    @GetMapping("isLogin")
    @ResponseBody
    public AjaxResult isLogin() {
        return AjaxResult.success(ShiroUtils.getSysUser());
    }

    /**
     * 登录页面
     *
     * @return
     */
    @GetMapping("login")
    public String login() {
        return prefix + "/login";
    }

    /**
     * 产品浏览页面加载
     *
     * @param mmap
     * @param productType
     * @return
     */
    @GetMapping("browseHP")
    public String browseHP(ModelMap mmap, @RequestParam(value = "productType", required = false) String productType) {
        //获取发布单位筛选条件
        List<SysDept> departs = sysDeptService.getAllDept();
        mmap.put("departs", departs);
        //获取要素筛选条件
        List<OForecastElement> ForecastElementEntity = forecastElementService.getAllForecastElement();
        mmap.put("forecastElementEntity", ForecastElementEntity);
        //获取海区筛选条件
        List<OOceanArea> oceanAreaEntity = oceanAreaService.getAllOceanArea();
        mmap.put("oceanAreaEntity", oceanAreaEntity);
        //获取模式筛选条件
        List<OMode> modeEntity = modeService.getAllMode();
        mmap.put("modeEntity", modeEntity);
        if (StringUtils.isNotBlank(productType)) {
            mmap.put("productType", productType);
        }
        return prefix + "/browseHP";
    }

    /**
     * 产品浏览页面数据获取
     *
     * @param productType
     * @param depart
     * @param oceanArea
     * @param element
     * @param mode
     * @param currentPage
     * @param request
     * @param response
     * @return
     */
    @PostMapping("getProduct")
    @ResponseBody
    public AjaxResult getProduct(@RequestParam(value = "productType", required = false) String productType,
                                 @RequestParam(value = "depart", required = false) String depart,
                                 @RequestParam(value = "oceanArea", required = false) String oceanArea,
                                 @RequestParam(value = "element", required = false) String element,
                                 @RequestParam(value = "mode", required = false) String mode,
                                 @RequestParam(value = "currentPage") int currentPage, HttpServletRequest request, HttpServletResponse response) {
//获取当前登录人的所属单位
        ForeResult result = productService.getProduct(productType, depart, oceanArea, element, mode, currentPage);
        return AjaxResult.success(result);
    }

    /**
     * 详情页面跳转
     *
     * @param productId
     * @param mmap
     * @return
     */
    @GetMapping("detail")
    public String detail(@RequestParam("productId") String productId, ModelMap mmap) {
        OProduct product = productService.selectOProductById(productId);
        if(product.getFrequency().equals("01")){//判断起报时间
            product.setFrequency("世界时00时");
        }else if(product.getFrequency().equals("02")){
            product.setFrequency("世界时12时");
        }else if(product.getFrequency().equals("03")){
            product.setFrequency("世界时00/12时");
        }else if(product.getFrequency().equals("04")){
            product.setFrequency("世界时16时");
        }else{
            product.setFrequency("世界时00时");
        }
        mmap.put("product", product);
        TSAttachment attachment = new TSAttachment();
        attachment.setBusinesskey(productId);
        List<TSAttachment> attachmentList = attachmentService.selectTSAttachmentList(attachment);
        mmap.put("attachments", attachmentList);
        return prefix + "/detail";
    }

    /**
     * L类产品跳转
     * @return
     */
    @GetMapping("ltype")
    public String Ltype() {
        return prefix + "/ltype";
    }

    @GetMapping("detailByName")
    public String detailByName(@RequestParam String productName, ModelMap mmap) {
        OProduct p = new OProduct();p.setProductName(productName);
        List<OProduct> products = productService.selectOProductList(p);
        if(products.get(0).getFrequency().equals("01")){//判断起报时间
            products.get(0).setFrequency("世界时00时");
        }else if(products.get(0).getFrequency().equals("02")){
            products.get(0).setFrequency("世界时12时");
        }else if(products.get(0).getFrequency().equals("03")){
            products.get(0).setFrequency("世界时00/12时");
        }else if(products.get(0).getFrequency().equals("04")){
            products.get(0).setFrequency("世界时16时");
        }else{
            products.get(0).setFrequency("世界时00时");
        }
        mmap.put("product", products.get(0));
        TSAttachment attachment = new TSAttachment();
        attachment.setBusinesskey(products.get(0).getId());
        List<TSAttachment> attachmentList = attachmentService.selectTSAttachmentList(attachment);
        mmap.put("attachments", attachmentList);
        return prefix + "/detail";
    }

    /**
     * 获取详情中nc文件列表数据
     *
     * @param productId
     * @param currentPage
     * @return
     */
    @PostMapping("getNcFile")
    @ResponseBody
    public AjaxResult getNcFile(@RequestParam String productId, @RequestParam int currentPage) {
        ForeResult result = ncFileService.getNcFile(productId, currentPage);
        return AjaxResult.success(result);
    }

    /**
     * 订阅页面跳转
     *
     * @param productId
     * @param mmap
     * @return
     */
    @GetMapping("subscription/{productId}")
    public String subscription(@PathVariable String productId, ModelMap mmap) {
        if(productId==null){
            return "错误，id为空";
        }
        //判断是否是智能网格
        if(productId.contains(Config.ZNWG.getZnwg())){
            String[] split = productId.split("_");
            ONCfileMenu getnr = onCfilemeunService.getnrvalue(split[1]);

            OProduct product = new OProduct();
            product.setId(productId);
            product.setFileType(getnr.getGs());
            mmap.put("product", product);
           // mmap.put("productId",productId);
            List<OForecastElement> list = new ArrayList<>();
            OForecastElement element = new OForecastElement();
            element.setElementName(getnr.getName());
            element.setEnglishAbbreviations(Config.ZNWG.getZnwg()+getnr.getValue());
            list.add(element);
            mmap.put("elementList", list);
        }else {
            OProduct product = productService.selectOProductById(productId);
            mmap.put("product", product);
            List<OForecastElement> list = new ArrayList<>();
            OForecastElement element = new OForecastElement();
            element.setEnglishAbbreviations(product.getForecastElement());
            element.setElementName(product.getElementName());
            list.add(element);
            mmap.put("elementList", list);
        }
        return prefix + "/subscription";
    }

    /**
     * 获取订阅数据
     *
     * @param productId
     * @return
     */
    @PostMapping("getSubscribeData")
    @ResponseBody
    public AjaxResult getSubscribeData(@RequestParam String productId) {
        Map<String, Object> map = new HashMap<>();
        List<OMetadataElement> eList = metadataElementService.selectOMetadataElementByProductId(productId);
        map.put("param", eList);
        List<String> dateList = ncFileService.getNcFileDate(productId);
        map.put("ncFileDate", dateList);
        return AjaxResult.success(map);
    }

    /**
     * 订阅功能
     *
     * @param workOrder
     * @return
     */
    @PostMapping("createWork")
    @ResponseBody
    public AjaxResult createWork(@RequestBody OWorkOrder workOrder) {
        System.out.println(workOrder);
        return workOrderService.createWork(workOrder);
    }

    // 缓存，用于存储请求参数和时间戳
    private static ConcurrentHashMap<String, Long> requestCache = new ConcurrentHashMap<>();
    // 设置缓存过期时间（5秒）
    private static final long CACHE_EXPIRATION_TIME = TimeUnit.SECONDS.toMillis(5);

    public static boolean handleRequest(String parameter) {
        // 获取当前时间戳
        long currentTime = System.currentTimeMillis();

        // 从缓存中获取参数的时间戳
        Long cachedTime = requestCache.get(parameter);

        if (cachedTime != null) {
            System.out.println(currentTime);
            System.out.println(cachedTime);
            System.out.println(currentTime - cachedTime);
            // 如果缓存中存在时间戳，并且没有过期
            if (currentTime - cachedTime < CACHE_EXPIRATION_TIME) {
                // 跳过处理
                System.out.println("Request with parameter '" + parameter + "' skipped due to recent duplicate.");
                return false;
            }
        }

        // 更新缓存
        requestCache.put(parameter, currentTime);
        // 如果缓存中不存在时间戳，或者时间戳已过期
        // 执行正常的处理逻辑
    return true;
    }

/*    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        boolean b = handleRequest("time");
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        System.out.println(b);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                boolean b = handleRequest("time");
                System.out.println(b);
            }
        };

        scheduler.schedule(task, 2, TimeUnit.SECONDS);

        // 记得在不再需要时关闭scheduler
        scheduler.shutdown();
    }*/
String fileIdpd = "";
String productIdpd = "";
    /**
     * 下载nc文件
     *
     * @param fileId
     * @param productId
     * @return
     */
    @GetMapping("download")
    @ResponseBody
    public void download(@RequestParam String fileId, @RequestParam String productId, HttpServletResponse response) {
        //=====================================
        fileIdpd = fileId;
        productIdpd = productId;
        //long l = System.currentTimeMillis();
                if(productIdpd.equals(productId)){
                    boolean b = handleRequest("time");
                    System.out.println("下载文件防止重复"+b);
                    if(b == false) {//防止五秒内重复提交(如果部署到服务器正常可以去掉这个判断)
                        System.out.println("下载文件防止重复1"+b);
                        return;
                    }
                }
            //================================
            String path = ncFileService.download(fileId, productId);
            //String path="D:\\cloud\\ocean\\NMF\\BEN\\OSMWA\\NWPACDT\\NMF_BEN_OSMWA_NWPACDT_2025010212_168h_WAVT01.nc";
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename="
                    + filename);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            InputStream bis = null;
            BufferedOutputStream bos = null;
            //记录统计下载日志↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
            ODownOrder downOrder = new ODownOrder();
            downOrder.setId(UUID.randomUUID().toString());//id
            downOrder.setCreateDate(new Date());//创建时间
            downOrder.setResourcePath(path);//地址
            downOrder.setDownEndDate(new Date());//下载结束时间 //有这个字段证明下载完成
            downOrder.setUserId(ShiroUtils.getSysUser().getUserId().toString());    //添加用户id

            downOrder.setWorkNo(System.currentTimeMillis() + "");
            // downOrder.setUserId();//userId
            downOrderService.insertODownOrder(downOrder);
            //记录统计下载日志↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
            //文件下载↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
            try {
                bis = new BufferedInputStream(new FileInputStream(path));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        //文件下载↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    }

    /**
     * 预览功能
     * @param productId
     * @return
     */
    @PostMapping("isPreview")
    @ResponseBody
    public AjaxResult isPreview(@RequestParam String productId) {
        OProduct product = productService.selectOProductById(productId);
        return AjaxResult.success(product);
    }
    @RequestMapping("toPreviews")
    public String toPreviews(@RequestParam String productId, @RequestParam String id,
                                   @RequestParam String fileName,@RequestParam String updateDate,ModelMap mmap) {
        OProduct product = productService.selectOProductById(productId);

        mmap.put("productId", productId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat inputSdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        // 本取发布时间  后又改为取当天时间
//        String time = sdf.format(productRelease.getReleaseDate());
        String time = sdf.format(new Date());
        mmap.put("time", time);
        mmap.put("productName", product.getProductName());
        if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(updateDate)){
            mmap.put("ncFileId", id);
            mmap.put("ncFileName", fileName);
            mmap.put("ncFileUpdateDate",updateDate);
        }
        if("ppt".equals(product.getFileType()) ||"pptx".equals(productId) ||
                "xls".equals(product.getFileType()) ||"xlsx".equals(product.getFileType()) ||
                "txt".equals(product.getFileType()) || "doc".equals(product.getFileType())||
                "docx".equals(product.getFileType())){
            return prefix+"/yulanother";
        }else if("pdf".equals(product.getFileType()) ){ // pdf预览
            return prefix+"/yulanpdfother";
        }else{ // 走原来的方法
            return prefix+"/yulan";
        }
    }

    /**
     * 获取预览数据
     * @param productId
     * @return
     */
    @PostMapping("getPreviewData")
    @ResponseBody
    public AjaxResult getPreviewData(@RequestParam String productId){
        List<OMetadataElement> list = metadataElementService.selectOMetadataElementByProductId(productId);
        List<String> ncFileDate = ncFileService.getNcFileDate(productId);
        Map<String, Object> map = new HashMap<>();
        map.put("param", list);
        map.put("ncFileDate", ncFileDate);
        return AjaxResult.success(map);
    }

    /**
     * 产品预览 结果页面跳转
     * @return
     */
    @GetMapping("result")
    public String result(){
        return prefix+"/yulanResult";
    }

    @PostMapping("preview")
    @ResponseBody
    public AjaxResult preview(PreviewData previewData){
        return ncFileService.createXmlFile(previewData);
    }

    @PostMapping("isExitLocalFile")
    @ResponseBody
    public AjaxResult isExitLocalFile(@RequestParam String ncFileId){
        Map<String, Object> map = new HashMap<>();
        ONcFile ncFile = ncFileService.selectONcFileById(ncFileId);
        String oldFilePath = ncFile.getFilePath() + File.separator + ncFile.getFileName();
        File file = new File(oldFilePath);
        if (file.exists()) { //存在
            map.put("message", "");
            map.put("flag", true);
        }else{//不存在
            map.put("message", ""); //未找到服务器中存储的文件，请确认文件在服务器中是否真的存在
            map.put("flag", false);
        }
        return AjaxResult.success(map);
    }

    @GetMapping("resultother")
    public String resultother(@RequestParam String productId,@RequestParam String fileId,ModelMap mmap) throws ParserConfigurationException, TransformerException, IOException {
        String url = "";
        ONcFile ncFile = ncFileService.selectONcFileById(fileId);
        String oldFilePath=ncFile.getFilePath() + File.separator + ncFile.getFileName();

        String oldFileName = ncFile.getFileName();

        String prefixFileName = oldFileName.substring(0,oldFileName.lastIndexOf(".")); //获取前缀名
        String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);   // 获取后缀类型(ppt、txt、doc或者docx)

        if("pdf".equals(suffixName)){ // pdf 预览
            // url = "web/yulanpdfother";
            url = "web/yulanResultOther";
        }else{ // 其他格式( 除NC外 )预览
            url = "web/yulanResultOther";
        }

        String resultFilePath =""; //最终返回的文件路径
        if("ppt".equals(suffixName)){ // 如果是 ppt
            //先检测文件是否生成，如果没有文件，则生成文件，如果已经存在，直接返回文件路径。
            String tempPath= ConStant.PREVIEW_BASEPATH+ConStant.PPT_CONSTANT+File.separator+ConStant.PPT_PREVIEW_BASEPATH+ File.separator +prefixFileName+File.separator +prefixFileName+".html";
            //String tempPath= "/cloud/ocean/NMF/"+ConStant.PPT_CONSTANT+File.separator+ConStant.PPT_PREVIEW_BASEPATH+ File.separator +prefixFileName+File.separator +prefixFileName+".html";
            File tempFile =new File(tempPath);
            if(tempFile.exists()){
                resultFilePath = ConStant.PPT_CONSTANT+File.separator +ConStant.PPT_PREVIEW_BASEPATH+ File.separator +prefixFileName+File.separator +prefixFileName+".html";
            }else{
                resultFilePath = PptToHtmlUtils.pptToPicture(oldFilePath, ConStant.PREVIEW_BASEPATH+ConStant.PPT_CONSTANT+ File.separator +ConStant.PPT_PREVIEW_BASEPATH, ncFile.getFileName());
                //resultFilePath = PptToHtml.pptToPicture(oldFilePath, "/cloud/ocean/NMF/"+ConStant.PPT_CONSTANT+ File.separator +ConStant.PPT_PREVIEW_BASEPATH, fileEntity.getFileName());
            }
        }else if("txt".equals(suffixName)){  // 如果是 txt，txt 不需要转换，直接根据路径预览
            // 对路径进行截取
            String attrstemp =oldFilePath.replace("\\", ",").replace("/",",");
            String[] attrs = attrstemp.split(",");
            String name0 = attrs[attrs.length-4];
            String name1 = attrs[attrs.length-3];
            String name2 = attrs[attrs.length-2];
            String name3 = attrs[attrs.length-1];
            resultFilePath = name0+File.separator+name1+File.separator+name2+File.separator+name3;
        }else if("doc".equals(suffixName) || "docx".equals(suffixName)){  // 如果是 doc 或者  docx
            resultFilePath = WordToHtmlUtils.wordConvertToHtml(oldFilePath, ConStant.PREVIEW_BASEPATH+ConStant.DOC_CONSTANT+ File.separator , ncFile.getFileName());
        }else if("xls".equals(suffixName) || "xlsx".equals(suffixName)){  // 如果是 xls 或者  xlsx
            resultFilePath = PoiExcelToHtmlUtils.PoiExcelToHtml(oldFilePath, ConStant.PREVIEW_BASEPATH+ConStant.EXCEL_CONSTANT+ File.separator , ncFile.getFileName());
        }else if("pdf".equals(suffixName)){  // 如果是 pdf
            // 对路径进行截取
            String attrstemp =oldFilePath.replace("\\", ",").replace("/",",");
            String[] attrs = attrstemp.split(",");
            String name0 = attrs[attrs.length-4];
            String name1 = attrs[attrs.length-3];
            String name2 = attrs[attrs.length-2];
            String name3 = attrs[attrs.length-1];
            resultFilePath = name0+File.separator+name1+File.separator+name2+File.separator+name3;
        }

        //System.out.println("最终文件路径-----------> "+ resultFilePath );
        mmap.put("filePath", resultFilePath);

        // 预览新版本实现
        String originUrl = "http://cloud.oceanguide.org.cn/";
        originUrl +=  "introduce.do?download&fileId=" + fileId;
        String previewUrl = originUrl + "&fullfilename=" + oldFileName;
        previewUrl = "http://cloud.oceanguide.org.cn:8012/onlinePreview?url=" + EncodingUtil.encodeURIComponent(previewUrl);
        mmap.put("previewUrl", previewUrl);
        return url;
    }

    /**
     * 产品预览 结果页面跳转
     *
     * @param request
     * @return
     */
    @PostMapping("createWord")
    public void createWord(HttpServletRequest request,HttpServletResponse response) {
        String data = request.getParameter("data");
        String resultImg = request.getParameter("resultImg");
        PreviewData previewData = JSON.parseObject(data, PreviewData.class);
        File f = previewElementService.getPreviewWord(previewData,resultImg);
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            String agent = (String)request.getHeader("USER-AGENT");
            String fileName = "预览";
            if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
            {
                fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            }
            else
            {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/msword");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName+".doc");
            os = response.getOutputStream();
            fis = new FileInputStream(f);
            byte[] b = new byte[1024 * 10];
            int i = 0;
            while ((i = fis.read(b)) > 0) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 预览页跳转
     */
    @PostMapping(params = "toPreview")
    public String toPreview(@RequestParam String productId,ModelMap mmap) {
        String url = "web/yulanother";
        OProduct product = productService.selectOProductById(productId);
        if("ppt".equals(product.getFileType()) ||"pptx".equals(product.getFileType())
                || "xls".equals(product.getFileType()) ||"xlsx".equals(product.getFileType())
                ||"txt".equals(product.getFileType()) || "doc".equals(product.getFileType())
                || "docx".equals(product.getFileType())){
        }else if(product.getFileType().equals("pdf") ){ // pdf预览
            url = "web/yulanother";
        }else{ // 走原来的方法
            url = "web/yulan";
        }

        mmap.put("productId", productId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        // 本取发布时间  后又改为取当天时间
//        String time = sdf.format(productRelease.getReleaseDate());
        String time = sdf.format(new Date());
        mmap.put("time", time);
        mmap.put("productName", product.getProductName());
        return url;
    }
    /**
     * 下载文件到浏览器
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(params = "onlineAllFile")
    public static void onlineAllFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "";
        String fileName = "";
        File  file = new File(filePath + File.separator + fileName);
        //  文件存在才下载
        if (file.exists()) {
            OutputStream out = null;
            FileInputStream in = null;
            try {
                // 1.读取要下载的内容
                in = new FileInputStream(file);

                // 2. 告诉浏览器下载的方式以及一些设置
                // 解决文件名乱码问题，获取浏览器类型，转换对应文件名编码格式，IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
                String agent = request.getHeader("user-agent");
                if (agent.contains("FireFox")) {
                    fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
                // 设置下载文件的mineType，告诉浏览器下载文件类型
                String mineType = request.getServletContext().getMimeType(fileName);
                response.setContentType(mineType);
                // 设置一个响应头，无论是否被浏览器解析，都下载
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                // 将要下载的文件内容通过输出流写到浏览器
                out = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            }
        }
    }

    @GetMapping(params = "download")
    public void download(String fileId, HttpServletRequest request,
                         HttpServletResponse response) {
        System.out.println(fileId);
        String path = productService.downLoad(fileId);
        File file = new File(path);
        // 取得文件名。
        String filename = file.getName();
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment; filename="
                + filename);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        InputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 跳转解压下载页面
     */
    @GetMapping(params = "toUnzip")
    public String toUnzip(@RequestParam String ncFileId,ModelMap mmap) {
        ONcFile ncFile = ncFileService.selectONcFileById(ncFileId);
        mmap.put("ncFile", ncFile);
        return prefix + "/productUnzip";
    }

    /**
     * 跳转比测图片页面
     */
    @GetMapping(params = "toShowImage")
    public String toShowImage(@RequestParam String imageProductId,ModelMap mmap) {
        mmap.put("imageProductId", imageProductId);
        return prefix + "/showImage";
    }

    /**
     * 一键续订产品
     */
    @RequestMapping(params = "renewalProduct")
    @ResponseBody
    public AjaxResult renewalProduct(@RequestBody OWorkOrder workOrder) {
        return workOrderService.renewalProduct(workOrder);
    }

    /**
     * 通过ncFileId获取解压的文件
     */
    @PostMapping("getUnzip")
    @ResponseBody
    public AjaxResult getUnzip(@RequestParam String ncFileId) {
        List<ONcUnzip > result = ncUnzipService.getUnzip(ncFileId);
        return AjaxResult.success(result);
    }

    /**
     * 下载解压文件
     * @param unzipId
     * @param request
     * @param response
     */
    @RequestMapping(params = "downloadUnzip")
    public void downloadUnzip(@RequestParam String unzipId, HttpServletRequest request,
                              HttpServletResponse response) {
        System.out.println(unzipId);
        String path = ncUnzipService.downloadUnzip(unzipId);
        File file = new File(path);
        // 取得文件名。
        String filename = file.getName();
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment; filename="
                + filename);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        InputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过ncFileId获取比测图片
     */
    @PostMapping(params = "getImageList")
    @ResponseBody
    public AjaxResult getImageList(@RequestParam String ncFileId) {
        List<OProductImage> list = productImageService.getImageList(ncFileId);
        return AjaxResult.success(list);
    }

    /**
     * 通过ncFileId获取比测图片
     */
    @RequestMapping(params = "onlineDownloadFile")
    public void onlineDownloadFile(
            HttpServletRequest request, HttpServletResponse response) {
        // 获取HttpServletResponse
        String fileId = request.getParameter("fullfilename");
        String filePath = fileId.split(",")[0];
        String fileName = fileId.split(",")[1];
        if (fileId != null) {
            // 设置文件路径
            File file = new File(filePath+"/"+fileName);
            if (file.exists()) {
                // 设置HTTP响应头
                response.reset();
                try {
                    OutputStream os = response.getOutputStream();
                    // 读取文件
                    InputStream in = new FileInputStream(file);
                    // copy文件
                    IOUtils.copy(in, os);
                    in.close();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String tarFilePath = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCB\\NWPACDT\\NMF_BEN_OSM_CSDT_2024122212_072h_WAV.tar"; // 替换为你的tar文件路径
        try (InputStream is = Files.newInputStream(new File(tarFilePath).toPath());
             TarArchiveInputStream tarInput = new TarArchiveInputStream(is)) {
            TarArchiveEntry entry;
            while ((entry = tarInput.getNextTarEntry()) != null) {
                System.out.println(entry.getName());
                // 忽略目录条目
                if (entry.isDirectory()) {
                    continue;
                }
            }
        }
    }
}
